package com.ruoyi.business.appuser.config;

import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

/**
 * Swagger2的接口配置
 *
 * @author ruoyi
 */
@Configuration
public class WxpayConfigConfig {


    @Value("${wxpay.mchSerialNo}")
    private String mchSerialNo;
    @Value("${wxpay.apiKey3}")
    private String apiKey3;
    @Value("${wxpay.mchId}")
    private String mchId;
    @Value("${wxpay.keyPathSecret}")
    private String keyPathSecret;


    // WxPayV3 配置的 Verifier
    @Bean
    public Verifier getVerifier() throws Exception {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(keyPathSecret);
        CertificatesManager wxpayCertificatesManager = CertificatesManager.getInstance();
        try {

            // 为 WxPayV3 增加商户信息到证书管理器
            wxpayCertificatesManager.putMerchant(mchId,
                    new WechatPay2Credentials(mchId,
                            new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
                    apiKey3.getBytes(StandardCharsets.UTF_8));
        } catch (IOException | GeneralSecurityException | HttpCodeException e) {
            throw new RuntimeException(e);
        }

        // 返回 WxPayV3 的 Verifier
        return wxpayCertificatesManager.getVerifier(mchId);
    }


}
